package com.smalls.redshoes.ui.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.smalls.newvideotwo.NewDTVApp;
import com.smalls.newvideotwo.adapter.AllPageLeftAdapter;
import com.smalls.newvideotwo.base.BaseActivity;
import com.smalls.newvideotwo.mvp.bean.LiveChannel;
import com.smalls.newvideotwo.mvp.beanResult.GetChannelsResult;
import com.smalls.newvideotwo.mvp.presenter.GetChannelPresenter;
import com.smalls.newvideotwo.mvp.view.IGetChannelView;
import com.smalls.newvideotwo.util.LogUtil;
import com.smalls.newvideotwo.utils.Constant;
import com.smalls.newvideotwo.utils.Utils;
import com.smalls.redshoes.R;
import com.smalls.redshoes.model.LiveProgramsResponseModel;
import com.smalls.redshoes.ui.fragment.LivePlayFragment;
import com.smalls.redshoes.ui.widget.LivePlayControlProgramsView.OnLiveProgramItemListener;
import com.uking.udppush.UKingPlayerMessageService;
import com.uking.ukingmodule.ukingjnic;
import com.uking.util.VKConstant;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static com.uking.util.VKConstant.DEFAULT_LIVE_PORT;

public class LivePlayActivity extends BaseActivity implements OnLiveProgramItemListener, IGetChannelView {
    private static String TAG = Constant.baddcoolio2tag?Constant.TAGPREFIXSTR + LivePlayActivity.class.getSimpleName():LivePlayActivity.class.getSimpleName();
    public static final long DELAY_CANCEL_CHANNEL_SEQUENCE_POP = 3000;
    public static final long DELAY_GET_USER_INPUT_NUMBER_TIME = 1500;
    public static final int INVALID_USER_INPUT_NUMBER = -1;
    public static final int MAX_USER_INPUT_NUMBER_LENGTH = 3;
    private static final int mOnePageMax = 200;
    private int mStart = 0;
    private int mEnd = mOnePageMax-1;
    private GetChannelPresenter mGetChannelPresenter = null;
    protected ServiceConnection connection = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            ((UKingPlayerMessageService.MyBinder) service).getService().startUdpListener(LivePlayActivity.this.getPort());
        }
    };
    protected boolean isBound = false;
    private ArrayList<LiveChannel> mDatas = new ArrayList<>();
    private Handler mGetUserInputNumberHanndler = new Handler();
    private Runnable mGetUserInputNumberRunnable = new Runnable() {
        public void run() {
            LivePlayActivity.this.changeChannel();
        }
    };
    private Toast mInvalidChannelNumberToast;
    private LivePlayFragment mLivePlayFragment;
    private View mLoadingView;
    private View mRootView;
    private int mUserInputNumber = INVALID_USER_INPUT_NUMBER;
    private PopupWindow mUserInputNumberPopupWindow;
    private StringBuilder mUserInputNumberSb = new StringBuilder();

    public int onSetContentView() {
        return R.layout.activity_live_play;
    }

    protected void initView(Bundle savedInstanceState) {
        this.mRootView = findViewById(R.id.activity_live_play_root);
        this.mLoadingView = findViewById(R.id.activity_home_loading_view);
    }

    protected void setListener() {
    }

    protected void processLogic(Bundle savedInstanceState) {
        requestData();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startFloatService();
        bindKBPlayerMsgServer();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopFloatService();
        unBindKBPlayerMsgServer();
    }

    public void onResume() {
        super.onResume();
    }

    public void onPause() {
        super.onPause();
    }

    public void onBackPressed() {
        if (this.mLivePlayFragment == null || this.mLivePlayFragment.getControlViewVisibility() != 0) {
            super.onBackPressed();
        } else {
            this.mLivePlayFragment.setControlViewGone();
        }
    }

    private void replacePlayFragment() {
        LogUtil.d(this.TAG, "replacePlayFragment");
        this.mLivePlayFragment = new LivePlayFragment();
        this.mLivePlayFragment.setOnLiveProgramItemListener(this);
        Bundle bundle = new Bundle();
        bundle.putSerializable(LivePlayFragment.EXTRA_DATAS, this.mDatas);
        this.mLivePlayFragment.setArguments(bundle);
        replaceFragment(R.id.activity_live_play_play_fragment, this.mLivePlayFragment);
        showTip();
    }

    private void showTip() {
        View view = getLayoutInflater().inflate(R.layout.live_toast_tip, null);
        TextView text = (TextView) view.findViewById(R.id.tv_live_tip);
        ((ImageView) view.findViewById(R.id.iv_live_tip)).setImageResource(R.mipmap.toast_smile);
        text.setText(R.string.live_play_menu_tip);
        Toast toast = new Toast(getApplicationContext());
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(view);
        toast.show();
    }

    @Override
    public void onSucceedGetChannel(GetChannelsResult result, int n) {
        LogUtil.d(TAG,"onSucceedGetChannel.");
        if(result!=null
                &&result.getData()!=null
                &&result.getData().size()>0) {
            List<LiveChannel> data = result.getData();

            mDatas.addAll(data);
            if(result.getData().size()==mOnePageMax) {
                mStart = mEnd+1;
                mEnd += mOnePageMax;
                mGetChannelPresenter.requestData(false,mStart,mEnd);
                return;
            }
            data.clear();
            Collections.sort(mDatas,new Comparator<LiveChannel>(){
                public int compare(LiveChannel arg0, LiveChannel arg1) {
                    if(arg0.getSequence()>arg1.getSequence()) {
                        return 1;
                    } else if(arg0.getSequence()==arg1.getSequence()) {
                        return 0;
                    } else {
                        return -1;
                    }
                }
            });
            //mDatas = (ArrayList<LiveChannel>) data;
            LogUtil.d(LivePlayActivity.this.TAG, "live datas=" + LivePlayActivity.this.mDatas);
            Toast.makeText(NewDTVApp.getApp(), R.string.load_data_success, Toast.LENGTH_SHORT).show();
            if (LivePlayActivity.this.mLivePlayFragment == null) {
                LivePlayActivity.this.replacePlayFragment();
            } else {
                LivePlayActivity.this.mLivePlayFragment.setDatas(LivePlayActivity.this.mDatas);
            }
            mLoadingView.setVisibility(View.GONE);
        }

    }

    @Override
    public void showErrDialogGetChannel(String str, int i) {
        Utils.toastDialog(LivePlayActivity.this, getString(R.string.get_channel_list_fail));
        LivePlayActivity.this.mLoadingView.setVisibility(View.GONE);
    }


    private void requestData() {
        this.mLoadingView.setVisibility(View.VISIBLE);
        LogUtil.d(this.TAG, "requestData");
        mGetChannelPresenter = new GetChannelPresenter(this);
        mGetChannelPresenter.requestData(false,mStart,mEnd);
    }

    private void changeChannel() {
        String number = getUserInputNumberStringBuilder().toString();
        if (number.length() > MAX_USER_INPUT_NUMBER_LENGTH) {
            number = number.substring(0, MAX_USER_INPUT_NUMBER_LENGTH);
        }
        int nubmberResult = Integer.parseInt(getPrettyNumber(number));
        this.mUserInputNumber = INVALID_USER_INPUT_NUMBER;
        this.mUserInputNumberSb = null;
        if (this.mDatas == null || this.mDatas.size() <= 0 || nubmberResult <= 0 || this.mDatas.size() < nubmberResult) {
            runOnUiThread(new Runnable() {
                public void run() {
                    LivePlayActivity.this.showInvalidChannelNumberToast();
                }
            });
        } else if (this.mLivePlayFragment != null && this.mLivePlayFragment.isAdded()) {
            this.mLivePlayFragment.changeProgram(nubmberResult);
        }
        runOnUiThread(new Runnable() {
            public void run() {
                LivePlayActivity.this.cancelUserInputNumberPop();
            }
        });
    }

    private void showInvalidChannelNumberToast() {
        this.mInvalidChannelNumberToast = Toast.makeText(this, getResources().getString(R.string.enter_num_error), Toast.LENGTH_SHORT);
        this.mInvalidChannelNumberToast.setGravity(17, 0, 0);
        this.mInvalidChannelNumberToast.show();
    }

    private void cancelInvalidChannelNumberToast() {
        if (this.mInvalidChannelNumberToast != null) {
            this.mInvalidChannelNumberToast.cancel();
            this.mInvalidChannelNumberToast = null;
        }
    }

    private void cancelUserInputNumberPop() {
        if (this.mUserInputNumberPopupWindow != null && this.mUserInputNumberPopupWindow.isShowing()) {
            this.mUserInputNumberPopupWindow.dismiss();
            this.mUserInputNumberPopupWindow = null;
        }
    }

    public String getPrettyNumber(String number) {
        return BigDecimal.valueOf((long) Integer.parseInt(number)).stripTrailingZeros().toPlainString();
    }

    public StringBuilder getUserInputNumberStringBuilder() {
        if (this.mUserInputNumberSb == null) {
            this.mUserInputNumberSb = new StringBuilder();
        }
        return this.mUserInputNumberSb;
    }

    private void showUserInputNumberPop(String number) {
        cancelUserInputNumberPop();
        TextView mUserInputNumberTv = null;
        if (this.mUserInputNumberPopupWindow == null) {
            View mUserInputNumberPopuWindowView = View.inflate(this, R.layout.layout_pop_user_input_number, null);
            mUserInputNumberTv = (TextView) mUserInputNumberPopuWindowView.findViewById(R.id.layout_pop_user_input_number_tv);
            this.mUserInputNumberPopupWindow = new PopupWindow(mUserInputNumberPopuWindowView, -2, -2);
        }
        if (!TextUtils.isEmpty(number)) {
            LogUtil.d(this.TAG, "number=" + number);
            mUserInputNumberTv.setText(number);
        }
        if (!this.mUserInputNumberPopupWindow.isShowing()) {
            this.mUserInputNumberPopupWindow.showAtLocation(this.mRootView, 53, 50, 80);
        }
    }

    private void onUserInputNumber(int keyCode) {
        LogUtil.d(this.TAG, "onUserInputNumber=" + keyCode);
        cancelInvalidChannelNumberToast();
        this.mUserInputNumber = keyCode - 7;
        getUserInputNumberStringBuilder().append(this.mUserInputNumber + "");
        String number = getUserInputNumberStringBuilder().toString();
        if (number.length() > MAX_USER_INPUT_NUMBER_LENGTH) {
            number = number.substring(0, MAX_USER_INPUT_NUMBER_LENGTH);
        }
        showUserInputNumberPop(number);
        this.mGetUserInputNumberHanndler.removeCallbacks(this.mGetUserInputNumberRunnable);
        this.mGetUserInputNumberHanndler.postDelayed(this.mGetUserInputNumberRunnable, DELAY_GET_USER_INPUT_NUMBER_TIME);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getRepeatCount() != 0) {
            return super.onKeyDown(keyCode, event);
        }
        switch (keyCode) {
            case KeyEvent.KEYCODE_0/*7*/:
            case KeyEvent.KEYCODE_1 /*8*/:
            case KeyEvent.KEYCODE_2 /*9*/:
            case KeyEvent.KEYCODE_3 /*10*/:
            case KeyEvent.KEYCODE_4 /*11*/:
            case KeyEvent.KEYCODE_5 /*12*/:
            case KeyEvent.KEYCODE_6 /*13*/:
            case KeyEvent.KEYCODE_7 /*14*/:
            case KeyEvent.KEYCODE_8 /*15*/:
            case KeyEvent.KEYCODE_9 /*16*/:
                if (this.mLivePlayFragment != null && this.mLivePlayFragment.isAdded() && this.mLivePlayFragment.getControlViewVisibility() == 0) {
                    return super.onKeyDown(keyCode, event);
                }
                onUserInputNumber(keyCode);
                return true;
            case KeyEvent.KEYCODE_DPAD_UP /*19*/:
            case KeyEvent.KEYCODE_DPAD_DOWN /*20*/:
                if (this.mLivePlayFragment != null && this.mLivePlayFragment.isAdded() && this.mLivePlayFragment.setControlViewVisible(keyCode)) {
                    return true;
                }
            case KeyEvent.KEYCODE_DPAD_CENTER /*23*/:
            case KeyEvent.KEYCODE_MENU /*82*/:
                if (this.mLivePlayFragment != null && this.mLivePlayFragment.isAdded()) {
                    this.mLivePlayFragment.updateControlViewVisibility();
                    break;
                }
        }
        return super.onKeyDown(keyCode, event);
    }

    public boolean onKeyUp(int keyCode, KeyEvent event) {
        return super.onKeyUp(keyCode, event);
    }

    protected void onErrorToastDialogCancel(String msg) {
        //super.onErrorToastDialogCancel(msg);
        if (this.mLivePlayFragment != null && this.mLivePlayFragment.isAdded()) {
            this.mLivePlayFragment.onErrorToastDialogCancel();
        }
    }

    public void onLiveProgramItemClicked(AdapterView<?> adapterView, View view, int position, long id) {
        if (this.mDatas != null && this.mDatas.get(position) != null) {
            showUserInputNumberPop((position + 1) + "");
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    LivePlayActivity.this.cancelUserInputNumberPop();
                }
            }, DELAY_CANCEL_CHANNEL_SEQUENCE_POP);
        }
    }

    protected int getPort() {
        return DEFAULT_LIVE_PORT;
    }

    protected void bindKBPlayerMsgServer() {
        isBound=bindService(new Intent(this, UKingPlayerMessageService.class), this.connection, Context.BIND_AUTO_CREATE);
    }

    protected void unBindKBPlayerMsgServer() {
        if (this.connection != null&&isBound) {
            unbindService(this.connection);
            connection = null;
            this.isBound = false;
        }
    }
}
